//
//  HLMyEyesViewController.m
//  Various
//
//  Created by HarwordLiu on 16/4/6.
//  Copyright © 2016年 Harword. All rights reserved.
//

#import "HLMyEyesViewController.h"
#import "MyEyesTableViewCell.h"
#import "HLNetWorkTool.h"
#import "MyEyesSectionModel.h"
#import "HLDownloadMananger.h"
#import <FMDB.h>

@interface HLMyEyesViewController ()<UITableViewDelegate, UITableViewDataSource, MyEyesTableViewCellDelegate, HLDownloadManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *nextPageUrl;
@property (nonatomic, copy) NSString *nextPublishTime;

@property (nonatomic, strong) NSMutableArray *arrModel;

@property (nonatomic, strong) NSMutableArray *arrCollectionModel;

@property (nonatomic, strong) FMDatabase *dataBase;

@property (nonatomic, strong) HLDownloadMananger *downloadMananger;

@end

@implementation HLMyEyesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatSubView];
}
- (HLDownloadMananger *)downloadMananger{
    if (_downloadMananger == nil) {
        _downloadMananger = [HLDownloadMananger sharedMananger];
        _downloadMananger.delegate = self;
    }
    return _downloadMananger;
}

- (void)creatSubView {
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self creatTableSqlite];
    [self setRefresh];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSArray *arrCell = [self.tableView visibleCells];
    for (MyEyesTableViewCell *cell in arrCell) {
        [cell cellOffset];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [UIScreen mainScreen].bounds.size.height / 3;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.arrModel.count;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MyEyesSectionModel *model = self.arrModel[section];
    return model.videoListModel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"MyEyesTableViewCell";
    MyEyesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[MyEyesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    MyEyesSectionModel *modelSection = [[MyEyesSectionModel alloc] init];
    MyEyesCellModel *modelRow = [[MyEyesCellModel alloc] init];
    if (self.arrModel.count != 0) {
        
        modelSection = self.arrModel[indexPath.section];
        modelRow = modelSection.videoListModel[indexPath.row];
    }
    cell.model = modelRow;
    cell.delegate = self;
    return cell;
}
#pragma mark - cellDelegate
- (void)clickCellDownloadBtn:(UIButton *)sender sentCell:(MyEyesTableViewCell *)cell{
    if (sender.selected == YES) {
        
    } else {
        
        [self.downloadMananger downLoadMovie:cell.model];
        [self.downloadMananger resume_];
    }
}

#pragma mark - ManangerDelegate
- (void)changeProgress:(CGFloat)progress WithModel:(MyEyesCellModel *)model {
    NSArray *arrCell = [self.tableView visibleCells];
    for (MyEyesTableViewCell *cell in arrCell) {
        if (cell.model.ID == model.ID) {
            cell.coverView.frame = CGRectMake(progress * FXCWEIGHT, 0, FXCWEIGHT - progress * FXCWEIGHT, FXCHEIGHT / 3);
            [cell.downLoadBtn setImage:nil forState:UIControlStateNormal];
            [cell.downLoadBtn setTitle:[NSString stringWithFormat:@"%.1f%%", progress * 100] forState:UIControlStateNormal];
        }
    }
}

#pragma mark - 添加下拉刷新上拉加载
- (void)setRefresh{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh:)];
    NSMutableArray *arrImages = [NSMutableArray array];
    [arrImages addObject:[UIImage imageNamed:@"myEyes"]];
    [header setImages:arrImages forState:MJRefreshStateIdle];
    [header setImages:arrImages forState:MJRefreshStatePulling];
    [header setImages:arrImages forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    
    header.stateLabel.font = [UIFont fontWithName:@"Lobster1.4" size:15];
    header.stateLabel.textColor = [UIColor blackColor];
    
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh:)];
    // 为了进入时不显示footer
    footer.hidden = YES;
    self.tableView.mj_footer = footer;
    
    
    
    
}

- (void)headerRefresh:(MJRefreshGifHeader *)header {
    @synchronized(self) {
        
        
        // 初始化数组
        self.arrModel = [NSMutableArray array];
        // 获取系统时间
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyyMMdd"];
        NSDate *date = [NSDate date];
        NSString *dateString = [dateFormatter stringFromDate:date];
        [self getDataSourceFromWeb:[NSString stringWithFormat:NETEYES, dateString]];
        [header setTitle:self.nextPublishTime forState:MJRefreshStateIdle];
        [header setTitle:self.nextPublishTime forState:MJRefreshStateRefreshing];
        [header setTitle:self.nextPublishTime forState:MJRefreshStatePulling];
        // 显示联网状态旋转圆圈
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        [self.tableView.mj_header endRefreshing];
    }
    
}

- (void)footerRefresh:(MJRefreshFooter *)footer {
    [self getDataSourceFromWeb:self.nextPageUrl];
    // 显示联网状态旋转圆圈
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [footer endRefreshing];
}

// 数据刷新
- (void)getDataSourceFromWeb:(NSString *)url{
    
    //    NSLog(@"%@", url);
    [HLNetWorkTool getWithURL:url Parameter:nil HttpHeader:nil ResponseType:ResponseTypeJSON Progress:^(NSProgress *progress) {
        
    } Success:^(id result) {
        NSMutableArray *arrModel = [MyEyesSectionModel getMyEyesSectionModelFromDataArr:[result valueForKey:@"dailyList"]];
        for (MyEyesCellModel *model in arrModel) {
            [self.arrModel addObject:model];
        }
        self.nextPageUrl = [result valueForKey:@"nextPageUrl"];
        
        NSString *dateStr = [NSString stringWithFormat:@"%@", [result valueForKey:@"nextPublishTime"]];
        NSInteger dateInteger = [dateStr integerValue];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateInteger / 1000];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formatter setDateFormat:@"下次更新时间 MM-dd HH:mm"];
        self.nextPublishTime = [formatter stringFromDate:date];
        [self.tableView reloadData];
        // 关闭联网状态旋转圆圈
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        // 打开上拉加载
        self.tableView.mj_footer.hidden = NO;
    } Failure:^(NSError *error) {
#pragma mark - 添加弹窗网络连接失败
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self getDataSourceFromWeb:url];
        }];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络连接失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        NSLog(@"%@", error);
    }];
}

#pragma mark - 已下载

// 建表查询收藏的模型数组
- (void)creatTableSqlite {
    self.arrCollectionModel = [NSMutableArray array];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingString:@"/Vision.sqlite"];
    NSLog(@"%@", path);
    FMDatabase *dataBase = [FMDatabase databaseWithPath:path];
    self.dataBase = dataBase;
    BOOL open = [dataBase open];
    if (open) {
        [dataBase executeUpdate:@"CREATE TABLE IF NOT EXISTS t_MyEyesCellModel (ID integer, duration integer, idx integer, date integer, title text, webUrl text, rawWebUrl text, playUrl text, descriptionText text, category text, coverBlurred text, coverForFeed text, coverForDetail text, coverForSharing text, collection integer, collectionCount integer, shareCount integer, replyCount integer, playCount integer, progress integer)"];
        
        FMResultSet *result = [dataBase executeQuery:@"SELECT * FROM t_MyEyesCellModel"];
        while (result.next) {
            MyEyesCellModel *model = [[MyEyesCellModel alloc] init];
            model.ID = [result intForColumn:@"ID"];
            model.duration = [result intForColumn:@"duration"];
            model.idx = [result intForColumn:@"idx"];
            model.date = [result intForColumn:@"date"];
            model.consumptionModel.collectionCount = [result intForColumn:@"collectionCount"];
            model.consumptionModel.shareCount = [result intForColumn:@"shareCount"];
            model.consumptionModel.replyCount = [result intForColumn:@"replyCount"];
            model.consumptionModel.playCount = [result intForColumn:@"playCount"];
            model.collection = [result intForColumn:@"collection"];
            
            model.title = [result stringForColumn:@"title"];
            model.webUrl = [result stringForColumn:@"webUrl"];
            model.rawWebUrl = [result stringForColumn:@"rawWebUrl"];
            model.playUrl = [result stringForColumn:@"playUrl"];
            model.descriptionText = [result stringForColumn:@"descriptionText"];
            model.category = [result stringForColumn:@"category"];
            model.coverBlurred = [result stringForColumn:@"coverBlurred"];
            model.coverForFeed = [result stringForColumn:@"coverForFeed"];
            model.coverForDetail = [result stringForColumn:@"coverForDetail"];
            model.coverForSharing = [result stringForColumn:@"coverForSharing"];
            
            model.progress = [result intForColumn:@"progress"];
            
            [self.arrCollectionModel addObject:model];
        }
        
        [dataBase close];
    }
}

- (void)collectionMyEyesCellModel:(MyEyesCellModel *)model {
    [self.arrCollectionModel addObject:model];
    ConsumptionModel *modelConsunmp = model.consumptionModel;
    BOOL open = [self.dataBase open];
    if (open) {
        modelConsunmp.shareCount = 0;
        BOOL result =[self.dataBase executeUpdate:@"INSERT INTO t_MyEyesCellModel (ID, duration, idx, date, title, webUrl, rawWebUrl, playUrl, descriptionText, category, coverBlurred, coverForFeed, coverForDetail, coverForSharing, collection, collectionCount, shareCount, replyCount, playCount, progress) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [NSNumber numberWithInteger:model.ID], [NSNumber numberWithInteger:model.duration], [NSNumber numberWithInteger:model.idx], [NSNumber numberWithInteger:model.date], model.title, model.webUrl, model.rawWebUrl, model.playUrl, model.descriptionText, model.category, model.coverBlurred, model.coverForFeed, model.coverForDetail, model.coverForSharing, [NSNumber numberWithInteger:model.collection], [NSNumber numberWithInteger:model.consumptionModel.collectionCount], [NSNumber numberWithInteger:model.consumptionModel.shareCount], [NSNumber numberWithInteger:model.consumptionModel.replyCount], [NSNumber numberWithInteger:model.consumptionModel.playCount], [NSNumber numberWithFloat:model.progress]];
        NSLog(@"%d", result);
        
        [self.dataBase close];
        
    }
}

- (void)deleteFromSqliteWithModel:(MyEyesCellModel *)model {
    BOOL open = [self.dataBase open];
    MyEyesCellModel *removeModel = [[MyEyesCellModel alloc] init];
    for (MyEyesCellModel *tempModel in self.arrCollectionModel) {
        if (tempModel.duration == model.duration) {
            removeModel = tempModel;
        }
    }
    [self.arrCollectionModel removeObject:removeModel];
    if (open) {
        BOOL result = [self.dataBase executeUpdateWithFormat:@"DELETE FROM t_MyEyesCellModel WHERE title = %@", model.title];
        NSLog(@"%d", result);
    }
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
